from store.IStoreService import IStoreService
from store.mysql.MySqlDb import MySqlDb


# MySQL 存储服务
class MySqlStoreService(IStoreService):

  def __init__(self, setting={}) -> None:
    self.db = MySqlDb(setting)

  def get_brands(self, *args, **kwargs):
    """获取所有的品牌
    """
    sql = 'SELECT * FROM `car_brand`'
    return self.db.query(sql)

  def get_series(self, count: int | None = None, *args, **kwargs):
    """获取所有的车型
    """
    if count:
      if count > 0:
        sql = f'select a.id,a.series_id from car_info a limit {count}'
      else:
        sql = 'select a.id,a.series_id from car_info a'
    else:
      sql = 'select a.id,a.series_id from car_info a where a.series_url is null'
    return self.db.query(sql)

  def insert_seriesId(self, *data):
    """插入一个车型信息并返回插入id

    Args:
        data (_type_): _description_
    """

    series_id, dcar_score = data
    data = { 'series_id': series_id, 'dcar_score': dcar_score}
    sql = 'insert into car_info (series_id, dcar_score) select %(series_id)s,%(dcar_score)s from dual where not exists (select series_id from car_info where series_id=%(series_id)s)'
    return self.db.insert(sql, data)

  def insert_brand(self, data):
    """插入一个品牌并返回插入id

    Args:
        data (Tuple): 插入参数和条件参数
    """
    sql = 'INSERT INTO car_brand (brand_id,unique_id,path,brand_name,pinyin,business_status,image_url,on_sale_series_count) select %s,%s,%s,%s,%s,%s,%s,%s where not exists (select brand_id from car_brand where brand_id=%s)'
    return self.db.insert(sql, data)

  def insert_info(self, data):
    """修改一个车型信息并返回影响行数

    Args:
        data (_type_): _description_
    """
    data, id = data
    sql = self.db.get_sql_by_update_dict('car_info', data, f'id={id}')
    data = tuple(data.values())
    return self.db.update(sql, data)

  def get_sql_by_update_dict(self, table, dic: dict, condition: str):
    """通过字典数据生成一个修改sql语句

    Args:
        table (str): 表名
        dic (dict): 数据字典
        condition (str): 条件
    """
    if len(table) < 0 or len(dic) < 0:
      return
    sql = f'update {table} set '
    dict_sql = ''
    for key in dic.keys():
      dict_sql += f'`{key}`=%s, '
    dict_sql = dict_sql.removesuffix(', ')
    sql += dict_sql
    if len(condition) > 0:
      sql += f' where {condition}'
    return sql
